package com.mike.uaa.core;

import cn.hutool.core.util.IdUtil;

import java.io.Serializable;
import java.time.Instant;
import java.util.Collection;

/**
 * @author z
 */
public interface Authentication extends Serializable {

    default String getTokenValue() {
        return IdUtil.fastSimpleUUID();
    }

    /**
     * Returns the time at which the token was issued.
     *
     * @return the time the token was issued or {@code null}
     */
    default Instant getIssuedAt() {
        return null;
    }

    default long getExpiresIn() {
        return -1;
    }

    /**
     * 获取主体信息
     * <p>
     * 可以为用户名、用户信息
     *
     * @return 返回主体信息
     */
    Object getPrincipal();

    /**
     * 获取用户凭证
     *
     * @return 返回用户凭证
     */
    Object getCredential();

    /**
     * 获取赋予用户的权限
     *
     * @return 用户拥有的权限集合
     */
    Collection<? extends GrantedAuthority> getAuthorities();

    /**
     * 返回当前认证对象是否经过认证
     *
     * @return <code>true</code>以经过身份认证
     */
    boolean isAuthenticated();

    /**
     * 设置认证状态
     *
     * @param authenticated 认证状态 <code>true</code> 为已经通过认证
     */
    void setAuthenticated(boolean authenticated);

    /**
     * 检查是否有权限访问
     *
     * @param candidateAuthority 待检测权限信息
     * @return 返回检查结果 <code>true</code>检查通过
     */
    default boolean checkAuthority(String candidateAuthority) {
        return getAuthorities().stream()
                .anyMatch(a -> a.getAuthority().equals(candidateAuthority));
    }

    /**
     * 检查是否有权限访问
     *
     * @param candidateAuthority 待检测权限信息
     * @return 返回检查结果 <code>true</code>检查通过
     */
    default boolean checkAuthority(GrantedAuthority candidateAuthority) {
        return getAuthorities().stream()
                .anyMatch(a -> a.equals(candidateAuthority));
    }
}
